import React, { useEffect } from 'react';

// intl
import { IntlProvider, IntlShape, createIntl } from 'react-intl';

// antd
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import enUS from 'antd/lib/locale-provider/en_US';

import en from './en';
import zh from './zh';
import { useStore } from '@/stores';

let i18n: IntlShape | null = null;

interface IProps {
  prefixCls?: string;
  children: React.ReactNode;
}
const Intl: React.FC<IProps> = props => {
  const { prefixCls } = props;

  const { lang = 'zh' } = useStore();

  useEffect(() => {
    i18n = createIntl({
      locale: lang,
      messages: lang === 'en' ? en : zh,
    });
  }, [lang]);

  return (
    <IntlProvider locale={lang} messages={lang === 'en' ? en : zh}>
      <ConfigProvider locale={lang === 'en' ? enUS : zhCN} prefixCls={prefixCls}>
        {props.children}
      </ConfigProvider>
    </IntlProvider>
  );
};

export const getLocalI18n = () => {
  if (i18n === null) {
    i18n = createIntl({
      locale: 'zh',
      messages: zh,
    });
  }

  return (id: keyof typeof zh, value?: Record<string, any>) => {
    try {
      return i18n?.formatMessage({ id }, value);
    } catch (e) {
      return id;
    }
  };
};

export default Intl;
